<template>
  <div>
    <input type='checkbox' class='input-checkbox' v-model='checked' @click='checkedAll'>全选
    <div v-for='checkb in checkboxData' :key="checkb.id">
      <input type='checkbox' name='checkboxinput' class='input-checkbox' v-model='checkboxModel' :value='checkb.id'>{{checkb.value}}
    </div>
  </div>
</template>
<script>
export default {
  methods: {
    checkedAll: function () {
      var _this = this
      console.log(_this.checked)
      if (this.checked) {
        _this.checkboxModel = []
        console.log(_this.checkboxModel)
      } else {
        _this.checkboxModel = []
        _this.checkboxData.forEach(function (item) {
          _this.checkboxModel.push(item.id)
        })
        console.log(_this.checkboxModel)
      }
    }
  },
  watch: {
    'checkboxModel': {
      handler: function (val, oldVal) {
        if (this.checkboxModel.length === this.checkboxData.length) {
          this.checked = true
        } else {
          this.checked = false
        }
      },
      deep: true
    }
  },
  data () {
    return {
      checkboxData: [{
        id: '1',
        value: '苹果'
      }, {
        id: '2',
        value: '荔枝'
      }, {
        id: '3',
        value: '香蕉'
      }, {
        id: '4',
        value: '火龙果'
      }],
      checkboxModel: ['1', '3', '4'],
      checked: false
    }
  },
  mounted () {
    console.log(this.checked)
    console.log(this.checkboxModel)
  }
}
</script>

<style scoped>

</style>
